<template>
  <view class="follow-page">
    <!-- 搜索框 -->
    <view class="search-section">
      <view class="search-box">
        <uni-icons type="search" size="18" color="#999"></uni-icons>
        <input
          v-model="searchKeyword"
          placeholder="搜索用户昵称或用户名"
          placeholder-style="color: #999"
          @input="onSearchInput"
          @confirm="onSearch"
        />
        <view v-if="searchKeyword" class="clear-btn" @click="clearSearch">
          <uni-icons type="clear" size="16" color="#999"></uni-icons>
        </view>
      </view>
    </view>

    <!-- 分页设置和排序 -->
    <view class="page-settings">
      <view class="page-size-group">
        <text class="switch-label">每页显示：{{ pageSize }}</text>
        <view class="size-options">
          <view
            v-for="size in pageSizeOptions"
            :key="size"
            :class="['size-btn', { active: pageSize === size }]"
            @click="changePageSize(size)"
          >
            {{ size }}
          </view>
        </view>
      </view>

      <!-- 排序控制 -->
      <view class="sort-group">
        <text class="sort-label">排序方式：</text>
        <view class="sort-btn" @click="toggleSortOrder">
          <text class="sort-text">{{ sortOrder === 'desc' ? '最近关注' : '最早关注' }}</text>
          <up-icon
            name="order"
            size="20"
            :color="sortOrder === 'desc' ? '#007AFF' : '#666'"
          ></up-icon>
        </view>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading && userList.length === 0" class="loading-container">
      <up-loading-icon :show="true" color="#007AFF"></up-loading-icon>
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 错误状态 -->
    <view v-else-if="error && userList.length === 0" class="error-container">
      <up-empty text="加载失败，请重试" mode="error" :show="true">
        <up-button size="small" text="重新加载" type="primary" @click="refreshData"></up-button>
      </up-empty>
    </view>

    <!-- 用户列表 -->
    <scroll-view v-else class="user-list" scroll-y>
      <!-- 空状态 -->
      <view v-if="userList.length === 0 && !loading" class="empty-container">
        <up-empty text="暂无关注的用户" mode="list" :show="true"></up-empty>
      </view>

      <!-- 用户卡片列表 -->
      <view v-else class="user-cards">
        <view
          v-for="user in userList"
          :key="user.ID || user.id"
          class="user-card"
          @click="goToUserProfile(user)"
        >
          <!-- 用户头像 -->
          <view class="avatar">
            <image :src="user.headerImg || '/static/images/logo.jpg'" mode="aspectFill" />
          </view>

          <!-- 用户信息 -->
          <view class="user-info">
            <text class="nickname">{{ user.nickName || user.userName }}</text>
            <text v-if="user.schoolName" class="school">{{ user.schoolName }}</text>
            <text v-if="user.majorName" class="major">{{ user.majorName }}</text>
            <text v-if="user.signature" class="signature">{{ user.signature }}</text>
          </view>

          <!-- 用户状态标识 -->
          <view class="user-status">
            <text class="status-text">已关注</text>
          </view>
        </view>
      </view>

      <!-- 分页信息和控制 -->
      <view v-if="userList.length > 0" class="pagination-section">
        <!-- 分页信息 -->
        <view class="page-info">
          <text class="info-text">
            已显示 {{ userList.length }} / {{ total }} 条数据
            {{ currentPage > 1 ? `（第${currentPage}页）` : '' }}
          </text>
        </view>

        <!-- 翻页按钮 -->
        <view class="page-controls">
          <view class="page-buttons">
            <view :class="['page-btn', { disabled: currentPage <= 1 }]" @click="goToPrevPage">
              <text>上一页</text>
            </view>
            <view class="page-indicator">
              <text>{{ currentPage }} / {{ totalPages }}</text>
            </view>
            <view :class="['page-btn', { disabled: !hasMore }]" @click="goToNextPage">
              <text>下一页</text>
            </view>
          </view>
        </view>

        <!-- 没有更多数据 -->
        <view v-if="!hasMore && userList.length > 0" class="no-more">
          <text class="no-more-text">没有更多数据了</text>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
  import { ref, computed } from 'vue';
  import { onLoad } from '@dcloudio/uni-app';
  import { UserService } from '@/services';

  // 数据状态
  const userList = ref([]);
  const loading = ref(false);
  const error = ref(false);
  const hasMore = ref(true);

  // 分页参数
  const currentPage = ref(1);
  const pageSize = ref(5); // 默认每页5条
  const total = ref(0);

  // 搜索相关
  const searchKeyword = ref('');
  const searchTimer = ref(null);

  // 排序相关
  const sortOrder = ref('desc'); // 默认倒序（最近关注）

  // 分页选项
  const pageSizeOptions = [5, 10, 20, 50];

  // 计算总页数
  const totalPages = computed(() => {
    return Math.ceil(total.value / pageSize.value);
  });

  // 页面加载时初始化
  onLoad(() => {
    loadData();
  });

  // 设置加载状态
  const setLoadingState = () => {
    loading.value = true;
    return true;
  };

  // 清除加载状态
  const clearLoadingState = () => {
    loading.value = false;
  };

  // 处理API响应
  const handleResponse = response => {
    const isSuccess =
      response &&
      (response.code === 200 || response.code === 0 || (response.data && response.data.list));

    if (!isSuccess) {
      throw new Error(response?.msg || `API返回错误码: ${response?.code}`);
    }

    const responseData = response.data || response;
    const newUsers = responseData.list || [];

    // 分页模式：每页数据替换显示
    userList.value = newUsers;
    total.value = responseData.total || newUsers.length;

    // 计算是否还有下一页
    const totalPages = Math.ceil(total.value / pageSize.value);
    hasMore.value = currentPage.value < totalPages;
  };

  // 加载数据
  const loadData = async () => {
    setLoadingState();

    try {
      error.value = false;
      const params = {
        page: currentPage.value,
        pageSize: pageSize.value,
        order: sortOrder.value,
        ...(searchKeyword.value && {
          nickName: searchKeyword.value,
          username: searchKeyword.value,
        }),
      };

      const response = await UserService.getFollowList(params);
      handleResponse(response);
    } catch (err) {
      console.warn('loadData error:', err);
      error.value = true;
      uni.showToast({ title: '加载失败，请重试', icon: 'error' });
    } finally {
      clearLoadingState();
    }
  };

  // 重置页面数据
  const resetPageData = () => {
    currentPage.value = 1;
    userList.value = [];
    hasMore.value = true;
  };

  const refreshData = () => {
    resetPageData();
    loadData();
  };

  // 搜索功能
  const onSearchInput = () => {
    if (searchTimer.value) clearTimeout(searchTimer.value);
    searchTimer.value = setTimeout(onSearch, 500);
  };
  const onSearch = () => {
    resetPageData();
    loadData();
  };
  const clearSearch = () => {
    searchKeyword.value = '';
    onSearch();
  };

  // 🔧 切换分页大小
  const changePageSize = newSize => {
    if (pageSize.value === newSize) return;

    pageSize.value = newSize;
    resetPageData();
    loadData();
    uni.showToast({
      title: `每页显示 ${newSize} 条`,
      icon: 'none',
    });
  };

  // 📄 手动翻页功能
  const goToPrevPage = () => {
    if (currentPage.value <= 1) return;
    currentPage.value--;
    loadData();
  };

  const goToNextPage = () => {
    if (!hasMore.value) return;
    currentPage.value++;
    loadData();
  };

  // 切换排序顺序
  const toggleSortOrder = () => {
    sortOrder.value = sortOrder.value === 'desc' ? 'asc' : 'desc';
    resetPageData();
    loadData();

    const orderText = sortOrder.value === 'desc' ? '最近关注' : '最早关注';
    uni.showToast({
      title: `切换到${orderText}`,
      icon: 'none',
    });
  };

  const goToUserProfile = user => {
    uni.showToast({ title: `查看 ${user.nickName} 的主页`, icon: 'none' });
  };
</script>

<style lang="scss" scoped>
  .follow-page {
    min-height: 100vh;
    background-color: #f5f5f5;
  }

  /* 搜索区域 */
  .search-section {
    background: white;
    padding: 20rpx 30rpx 30rpx 30rpx;
    border-bottom: 20rpx solid #f5f5f5;

    .search-box {
      display: flex;
      align-items: center;
      background: #f8f8f8;
      border-radius: 44rpx;
      padding: 20rpx 30rpx;

      input {
        flex: 1;
        margin-left: 20rpx;
        font-size: 28rpx;
        color: #333;
      }

      .clear-btn {
        margin-left: 20rpx;
        padding: 10rpx;
      }
    }
  }

  /* 分页设置样式 */
  .page-settings {
    background: white;
    padding: 20rpx 30rpx;
    border-bottom: 20rpx solid #f5f5f5;

    .page-size-group {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20rpx;

      .switch-label {
        font-size: 26rpx;
        color: #666;
      }

      .size-options {
        display: flex;
        gap: 10rpx;

        .size-btn {
          background: #e0e0e0;
          color: #666;
          padding: 8rpx 16rpx;
          border-radius: 16rpx;
          font-size: 22rpx;
          min-width: 60rpx;
          text-align: center;

          &.active {
            background: #007aff;
            color: white;
          }
        }
      }
    }

    .sort-group {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-top: 20rpx;
      border-top: 1px solid #f0f0f0;

      .sort-label {
        font-size: 26rpx;
        color: #666;
      }

      .sort-btn {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8rpx;
        padding: 12rpx 20rpx;
        background: #f8f8f8;
        border-radius: 32rpx;
        transition: all 0.3s ease;

        &:active {
          background: #e0e0e0;
          transform: scale(0.95);
        }

        .sort-text {
          font-size: 24rpx;
          color: #333;
          font-weight: 500;
        }
      }
    }
  }

  /* 状态容器 */
  .loading-container,
  .error-container,
  .empty-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 100rpx 30rpx;

    .loading-text {
      margin-top: 20rpx;
      font-size: 28rpx;
      color: #999;
    }
  }

  /* 用户列表 */
  .user-list {
    flex: 1;

    .user-cards {
      background: white;

      .user-card {
        display: flex;
        align-items: flex-start;
        padding: 20rpx;
        border-bottom: 1px solid #f0f0f0;
        min-height: 100rpx;

        &:last-child {
          border-bottom: none;
        }

        /* 头像 */
        .avatar {
          width: 80rpx;
          height: 80rpx;
          border-radius: 50%;
          overflow: hidden;
          margin-right: 20rpx;

          image {
            width: 100%;
            height: 100%;
          }
        }

        /* 用户信息 */
        .user-info {
          flex: 1;

          .nickname {
            display: block;
            font-size: 30rpx;
            font-weight: 600;
            color: #333;
            margin-bottom: 6rpx;
          }

          .school,
          .major {
            font-size: 24rpx;
            color: #666;
            margin-bottom: 4rpx;
          }

          .signature {
            display: block;
            font-size: 22rpx;
            color: #999;
            margin-top: 6rpx;
            line-height: 1.3;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 1;
            line-clamp: 1;
            -webkit-box-orient: vertical;
          }
        }

        /* 用户状态标识 */
        .user-status {
          margin-left: 20rpx;

          .status-text {
            font-size: 24rpx;
            color: #999;
            background: #f5f5f5;
            padding: 8rpx 16rpx;
            border-radius: 20rpx;
          }
        }
      }
    }
  }

  /* 分页区域 */
  .pagination-section {
    background: white;

    .page-info {
      display: flex;
      justify-content: center;
      padding: 20rpx;
      background: #f8f8f8;

      .info-text {
        font-size: 24rpx;
        color: #999;
      }
    }

    .page-controls {
      padding: 20rpx;
      border-bottom: 1px solid #f0f0f0;

      .page-buttons {
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 30rpx;

        .page-btn {
          background: #007aff;
          color: white;
          padding: 16rpx 32rpx;
          border-radius: 24rpx;
          font-size: 26rpx;
          min-width: 120rpx;
          text-align: center;

          &.disabled {
            background: #e0e0e0;
            color: #999;
          }
        }

        .page-indicator {
          background: #f0f0f0;
          color: #666;
          padding: 16rpx 24rpx;
          border-radius: 24rpx;
          font-size: 26rpx;
          font-weight: 600;
        }
      }
    }
  }

  /* 底部状态 */
  .no-more {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 40rpx;
    background: white;

    .no-more-text {
      font-size: 28rpx;
      color: #999;
    }
  }
</style>
